package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.ContactGroup;
import domain.IDAOContactGroup;

/**
 * Servlet implementation class ModifyContactGroupServlet
 */
public class ModifyContactGroupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ModifyContactGroupServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IDAOContactGroup dao = (IDAOContactGroup) context.getBean("daocontactgroup");
		String id = request.getParameter("id");
		RequestDispatcher reqDis = null;
		if( id != null){
			ContactGroup  group = dao.getContactGroup(Long.valueOf(id));
			if( group != null) {
				request.setAttribute("contactGroup", group );
				reqDis = request.getRequestDispatcher("modifyContactGroup.jsp");
			} else {
				request.setAttribute("errorMessage", "The contact group doesn't exist.");
				reqDis = request.getRequestDispatcher("errorPage.jsp");
			}
		}
		reqDis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IDAOContactGroup dao = (IDAOContactGroup) context.getBean("daocontactgroup");
		String id = request.getParameter("id");
		String groupName = request.getParameter("groupName");
		RequestDispatcher reqDis = null;
		if( id != null){
			dao.modifyContactGroup(Long.valueOf(id), groupName);
			reqDis = request.getRequestDispatcher("modifyContactGroup.jsp");
		} else {
			reqDis = request.getRequestDispatcher("errorPage.jsp");
		}
	}

}
